<template>
  <Page class="bg-[#f5f7fa] min-h-screen">
    <!-- 顶部蓝色渐变背景 -->
    <view
      class="fixed top-0 left-0 w-full z-[3] h-[250rpx] bg-gradient-to-b from-[#4CAF50] to-[#81C784]"
    ></view>

    <!-- 吸顶标题与导航栏 -->
    <view
      class="sticky top-0 z-30 w-[750rpx] box-border pt-[32rpx] pb-[0] bg-transparent"
    >
      <PageHeader title="" :showBack="true" :onlyBack="true" />
      <view
        class="text-[36rpx] w-full z-1 events-none text-center font-bold text-white mb-[24rpx] flex justify-center items-center"
      >
        <text>我的报名</text>
      </view>

      <!-- 导航选项：工厂招聘，日结招聘，悬赏任务，签到任务 -->
      <view
        class="flex overflow-x-auto gap-x-[18rpx] py-[10rpx] px-[32rpx] scrollbar-hide"
      >
      <template v-for="(nav, index) in navOptions" :key="index">
        <view
          v-if="index != 1"
          class="px-[28rpx] py-[12rpx] rounded-[24rpx] text-[26rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap flex-shrink-0 relative"
          :class="
            activeNav === index
              ? 'bg-gradient-to-r from-[#4CAF50] to-[#81C784] text-white font-bold shadow-md border-[#4CAF50]'
              : 'bg-white/80 text-[#4CAF50]/80 hover:bg-white'
          "
          @click="activeNav = index"
        >
          {{ nav }}
         
        </view>
      </template>
       
      </view>
    </view>
    <!-- 内容区 -->
    <view class="pt-[20rpx] pb-[32rpx] px-[0] mt-[30rpx]">
      <view class="p-[24rpx_32rpx] flex flex-col gap-y-[28rpx]">
        <!-- 空状态 -->
        <EmptyState
          v-if="currentItems.length === 0"
          :type="activeNav"
          @refresh="handleRefresh"
        />

        <!-- 报名内容列表 -->
        <PublishedItem
          v-for="(item, index) in currentItems"
          :key="item.id"
          :item="item"
          :type="activeNav"
          :recruitmentType="0"
          @reload="handleReload"
          @click="handleItemClick(item)"
          @viewDetails="handleViewStatus(item)"
          @cancel="handleCancelEnroll(item)"
          @delete="handleDelete"
          v-if="activeNav === 0"
        />

        <PublishedItem
          v-for="(item, index) in currentItems"
          :key="item.id"
          :item="item"
          :type="activeNav"
          :recruitmentType="1"
          @reload="handleReload"
          @click="handleItemClick(item)"
          @viewDetails="handleViewStatus(item)"
          @cancel="handleCancelEnroll(item)"
          @delete="handleDelete"
          v-if="activeNav === 1"
        />

        <DailyRecruitmentItem
          v-for="(item, index) in currentItems"
          :key="item.id"
          :item="item"
          :type="activeNav"
          @reload="handleReload"
          @click="handleItemClick(item)"
          @viewDetails="handleViewStatus(item)"
          @delete="handleDelete"
          v-if="activeNav === 2"
        />

        <BountyTaskItem
          v-for="(item, index) in currentItems"
          :key="item.id"
          :item="item"
          :type="activeNav"
          @reload="handleReload"
          @click="handleItemClick(item)"
          @viewDetails="handleViewStatus(item)"
          @cancel="handleCancelEnroll(item)"
          @delete="handleDelete"
          @submit = "processScoring(item)"
          v-if="activeNav === 3"
        />

        <CheckInTaskItem
          v-for="(item, index) in currentItems"
          :key="item.id"
          :item="item"
          :type="activeNav"
          @reload="handleReload"
          @click="handleItemClick(item)"
          @viewDetails="handleViewStatus(item)"
          @cancel="handleCancelEnroll(item)"
          @delete="handleDelete"
          v-if="activeNav === 4"
        />
      </view>

      <!-- 加载更多 -->
      <view
        v-if="currentItems.length > 0 && hasMore"
        class="flex justify-center mt-[20rpx] mb-[30rpx]"
      >
        <nut-button
          size="small"
          type="default"
          class="border-[#4CAF50] text-[#4CAF50] bg-transparent rounded-[20rpx] px-[36rpx] py-[10rpx] text-[24rpx] font-medium hover:bg-[#e8f5e9] transition-all duration-200 flex items-center justify-center"
          @click="handleLoadMore"
          :loading="loadingMore"
        >
          <IconFont
            v-if="loadingMore"
            name="load-more"
            size="20"
            class="mr-[10rpx] animate-spin"
          />
          <span>{{ loadingMore ? "加载中..." : "加载更多" }}</span>
        </nut-button>
      </view>

    </view>
  </Page>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
// 引入封装的组件
import PublishedItem from "@/pages/registration/components/PublishedItem.vue";
import DailyRecruitmentItem from "@/pages/registration/components/DailyRecruitmentItem.vue";
import BountyTaskItem from "@/pages/registration/components/BountyTaskItem.vue";
import CheckInTaskItem from "@/pages/registration/components/CheckInTaskItem.vue";
import EmptyState from "@/pages/post/components/EmptyState.vue";

import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";
import { post, getFullPath } from "@/utils/request";

// 导入构建时间
import { BUILD_TIME } from "@/utils/build-time";
import EvaluateModal from "@/components/EvaluateModal.vue";


// 评价弹窗相关
const evaluateModalVisible = ref(false);
const currentEvaluateUser = ref({});

// 用户信息
const userStore = useUserStore();
const { userInfo, locationObj } = storeToRefs(userStore);

// 导航选项
// const navOptions = ["工厂招聘", "日结招聘", "悬赏任务"];
const navOptions = ["工厂招聘", "特殊招聘", "日结招聘", "悬赏任务", "签到任务"];
const activeNav = ref(0);
const badgeCounts = ref([5, 3, 2, 1, 0]); // 各导航的未处理数量


const enrolledItems = ref<any>([[],[],[],[],[]]);
// 当前显示的内容
const currentItems = computed(() => {
  return enrolledItems.value[activeNav.value] || [];
});

const handleDelete = (item) => { 
  console.log("删除", item);
};
// 计算状态文本的方法
const getStatusText = (status) => {
  // 处理null或undefined的情况
  if (status === null || status === undefined) {
    return "";
  }

  // 根据不同status值返回对应状态
  switch (Number(status)) {
    case 0:
      return "未发布";
    case 1:
      return "已发布";
    case 2:
      return "进行中";
    case 3:
      return "已截止";
    case 4:
      return "已完成";
    case 5:
      return "已取消";
    default:
      return "未知状态"; // 处理未定义的status值
  }
};

// 时间戳转换
function formatTimestamp(timestamp) {
  const date = new Date(timestamp);
  // 提取各时间部分（注意月份从0开始，需+1）
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 补0成两位数
  const day = String(date.getDate()).padStart(2, "0");
  // const hours = String(date.getHours()).padStart(2, '0');
  // const minutes = String(date.getMinutes()).padStart(2, '0');
  // const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day}`;
}

// 加载状态管理
const loadingMore = ref(false);
const hasMore = ref(true);

// 监听导航切换
watch(activeNav, () => {
  getEnrolledList(activeNav.value);
  setTimeout(() => {
    console.log('activeNav ===>', activeNav.value, enrolledItems.value);
    console.log('currentItems ===>', currentItems);
  }, 300);
});

// 获取列表接口地址
const getListUrl = () => {
  switch (activeNav.value) {
    case 0:
      return "/recruitment/mySignUp";
    case 1:
      return "/recruitment/mySignUp";
    case 2:
      return "/recruitmentDaily/mySignUp";
    case 3:
      return "/task/mySignUp";
    case 4:
      return "/check/mySignUp";
    default:
      return "/enroll/all/list";
  }
};

// 处理列表项点击
const handleItemClick = (item) => {
  Taro.navigateTo({
    url: `/pages/enroll/detail?id=${item.id}&type=${activeNav.value}`,
  }).catch((err) => {
    console.error("跳转详情页失败：", err);
  });
};

// 处理取消报名
const handleCancelEnroll = (item) => {
  console.log("handleCancelEnroll === 》", item);
  console.log("currentActiveNav:", activeNav.value);
  console.log("userInfo:", userInfo.value);
  
  // 检查用户信息是否存在
  if (!userInfo.value || !userInfo.value.id) {
    console.error("用户信息不存在或缺少ID");
    Taro.showToast({
      title: "用户信息异常，请重新登录",
      icon: "none",
      duration: 2000,
    });
    return;
  }
  
  let url = '';
  if(activeNav.value === 0){
    url = '/recruitment/mySignUp';
  }
  if(activeNav.value === 1){
    url = '/recruitment/mySignUp';
  }
  if(activeNav.value === 2){
    url = '/recruitmentDaily/mySignUp';
  }
  if(activeNav.value === 3){
    url = '/task/registercancel';
  }
  if(activeNav.value === 4){
    url = '/check/registercancel';
  }
  console.log("取消报名请求URL:", url);
  console.log("请求参数:", {
    id: item.id,
    ids: [userInfo.value.id],
  });
  post(url, {
    id: item.id,
    ids: [userInfo.value.id],
    recruitmentType: activeNav.value
  }).then((res) => {
    console.log("取消报名结果：", res);
    if (res.code === 0) {
      Taro.showToast({
        title: "取消成功",
        icon: "success",
        duration: 2000,
      });
      getEnrolledList(activeNav.value);
    } else {
      Taro.showToast({
        title: res.msg || "取消失败",
        icon: "none",
        duration: 2000,
      });
    }
  }).catch((error) => {
    console.error("取消报名请求失败：", error);
    Taro.showToast({
      title: "网络异常，请重试",
      icon: "none",
      duration: 2000,
    });
  });
};

const handleReload = () => { 
  getEnrolledList(activeNav.value);
};

// 处理签到（仅签到任务）
const handleCheckIn = (item) => {
  if (activeNav.value !== 3) return;

  // 获取当前位置
  Taro.getLocation({
    type: "gcj02",
    success: (res) => {
      // 模拟位置校验
      const isValidLocation = true; // 实际项目中应与服务器校验

      if (isValidLocation) {
        post("/enroll/checkin/sign", {
          id: item.id,
          latitude: res.latitude,
          longitude: res.longitude,
        }).then((res) => {
          if (res.code === 200) {
            Taro.showToast({
              title: "签到成功",
              icon: "success",
              duration: 2000,
            });
            getEnrolledList(activeNav.value);
          } else {
            Taro.showToast({
              title: res.msg || "签到失败",
              icon: "none",
              duration: 2000,
            });
          }
        });
      } else {
        Taro.showToast({
          title: "不在签到范围内",
          icon: "none",
          duration: 2000,
        });
      }
    },
    fail: (err) => {
      console.error("获取位置失败：", err);
      Taro.showToast({
        title: "请开启位置权限",
        icon: "none",
        duration: 2000,
      });
    },
  });
};

// 查看状态详情
const handleViewStatus = (item) => {
  console.log("handleViewStatus ===>", item, activeNav.value);
  // 工厂招聘详情
  if (activeNav.value == 0 || activeNav.value == 1) {
    Taro.navigateTo({
      url: `pages-detail/post/recruit/factory-recruitment-detail?id=${item.id}&type=${activeNav.value}`,
    }).catch((err) => {
      console.error("跳转状态页失败：", err);
    });
  }

  // 日结招聘详情
  if (activeNav.value == 2) {
    Taro.navigateTo({
      url: `pages-detail/post/recruit/order-acceptance-detail?id=${item.id}&type=${activeNav.value}`,
    }).catch((err) => {
      console.error("跳转状态页失败：", err);
    });
  }

  // 悬赏任务详情
  if (activeNav.value == 3) {
    Taro.navigateTo({
      url: `pages/webs/task-details-reward-task-platform?id=${item.id}&type=${activeNav.value}`,
    }).catch((err) => {
      console.error("跳转状态页失败：", err);
    });
  }
  // 签到任务详情
  if (activeNav.value == 4) {
    Taro.navigateTo({
      url: `pages-detail/post/reward/checkin-task-detail?id=${item.id}&type=3`,
    }).catch((err) => {
      console.error("跳转状态页失败：", err);
    });
  }

};

// 刷新列表
const handleRefresh = () => {
  getEnrolledList(activeNav.value);
};

// 加载更多
const handleLoadMore = () => {
  if (loadingMore.value) return;

  loadingMore.value = true;
  // 模拟加载延迟
  setTimeout(() => {
    // 实际项目中应请求下一页数据
    loadingMore.value = false;
    hasMore.value = false; // 模拟没有更多数据
    Taro.showToast({
      title: "已加载全部",
      icon: "none",
      duration: 1500,
    });
  }, 1500);
};

// 获取报名列表数据
const getEnrolledList = (activeNav) => {
  const url = getListUrl();
  if (activeNav == 0 || activeNav == 1) {
    post(url, {
      pageNo: 1,
      pageSize: 100,
      type: 0,
      status: 0,
      recruitmentType: activeNav
      // 可添加分页参数
    }).then((res) => {
      console.log(`获取${activeNav}报名列表：`, res);
      // 根据activeNav的值来获取数据渲染：0-工厂，1-日结，2-悬赏，3-签到
      enrolledItems.value[activeNav] = res.data.map((item) => ({

        ...item.columns,
        id: item.columns.id,
        title: item.columns.position_name,
        status: item.columns.status === 0 ? "待面试" : "",
        statusClass:
        item.columns.status === 0 ? "bg-[#fff8e1] text-[#faad14]" : "",
        company: item.columns.corporate_name,
        location: item.columns.location,
        salary: `￥${item.columns.salary_min}-${item.columns.salary_max}/月`,
        enrollTime: item.columns.registrationTime, // 后端无对应字段
        interviewTime: "", // 后端无对应字段
        interviewAddress: "", // 后端无对应字段
        tags: item.columns.labels,
        contactPerson: item.columns.name, // 后端无对应字段
        contactPhone: "", // 后端无对应字段
        special: item.columns.recruitment_type == 1,
        member_id: item.columns.member_id,
        memberStatus: item.columns.memberStatus,
        rmId: item.columns.rmId
      }));
    })
  }
  // 日结
  if (activeNav == 2) {
    post(url, {
      pageNo: 1,
      pageSize: 100,
      status: 0,
      // 可添加分页参数
    }).then((res) => {
      console.log(`获取${activeNav}报名列表：`, res);
      // 根据activeNav的值来获取数据渲染：0-工厂，1-日结，2-悬赏，3-签到
      enrolledItems.value[activeNav] = res.data.map((item) => {
        return item.columns;
      });
    });
  }
  // 悬赏任务
  if (activeNav == 3) {
    post(url, {
      pageNo: 1,
      pageSize: 100,
      status: 0,
      // 可添加分页参数
    }).then((res) => {
      console.log(`获取${activeNav}报名列表：`, res);
      // 根据activeNav的值来获取数据渲染：0-工厂，1-日结，2-悬赏，3-签到
      enrolledItems.value[activeNav] = res.data.map((item) => ({
        ...item.columns,
        id: item.columns.id,
        title: item.columns.title,
        status: getStatusText(item.columns.status),
        statusClass: "", // 后端无对应字段，需根据status值自定义
        publisher: item.columns.memberName,
        reward: `￥${item.columns.total_amount}`,
        enrollTime: "", // 后端无对应字段
        acceptTime: "", // 后端无对应字段
        deadline: item.columns.deadline,
        progress: "", // 后端无对应字段
        tags: [item.columns.labels],
        submitCount: "", // 后端无对应字段
        lastSubmitTime: "", // 后端无对应字段
        tmId:item.columns.tmId,
        memberStatus: item.columns.memberStatus,
      }));
      console.log(enrolledItems.value);
    });
  }
  // 签到任务
  if (activeNav == 4) {
    post(url, {
      pageNo: 1,
      pageSize: 100,
      status: 0,
      // 可添加分页参数
    }).then((res) => {
      console.log(`获取${activeNav}报名列表：`, res);
      // 根据activeNav的值来获取数据渲染：0-工厂，1-日结，2-悬赏，3-签到
      enrolledItems.value[activeNav] = res.data.map((item) => {
        return item.columns;
      });
    });
  }
};

// 页面挂载时获取数据
onMounted(() => {
  getEnrolledList(activeNav.value);
});
</script>
